package com.xiia.admin.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.xiia.common.servlet.FrameworkServlet;
import com.xiia.servcie.imp.NewsHeadlineService;
import com.xiia.servcie.imp.NewsService;
import com.xiia.service.inter.INews;
import com.xiia.service.inter.INewsHeadline;
import com.xiia.util.ParamUtil;
import com.xiia.vo.News;
import com.xiia.vo.NewsHeadline;
import com.xiia.vo.User;

/**
 * 2014 11 7 15:12
 * @author 陈强
 * 头条servlet
 */
@WebServlet("/headline.do")
public class HeadlineServlet extends FrameworkServlet{
	private static final long serialVersionUID = 1L;
	private static INews iNews =new NewsService();
	private static INewsHeadline iNewsHeadline = new NewsHeadlineService();
	public HeadlineServlet(){
		 iNews =new NewsService();
		 iNewsHeadline = new NewsHeadlineService();
	}
	/**
	 * 从jsp中获取数据
	 * @param r
	 * @return NewsHeadline
	 */
	private NewsHeadline doForm(HttpServletRequest r){
		News news = new News();
		User u = new User();
		NewsHeadline newsHeadline =new NewsHeadline();
		if(null != r.getParameter("userName"))
		{
			u.setUserName(r.getParameter("userName"));
			newsHeadline.setUser(u);
		}
		if(null!=r.getParameter("newsId")){
			int newsId = Integer.parseInt(r.getParameter("newsId"));
			news = iNews.findNews(newsId);
			newsHeadline.setNews(news);
		}
		if(null!= r.getParameter("headUrl")){
			newsHeadline.setHeadUrl(r.getParameter("headUrl"));
		}
		return newsHeadline;
	}
	/**
	 * 添加头条信息
	 * @param req
	 * @param res
	 * @return String
	 */
	public String addHeadline(HttpServletRequest req,
			HttpServletResponse res){
		String headline_title= req.getParameter("headline_title");
		String headline_note = req.getParameter("headline_note");

			int sortId = Integer.parseInt(req.getParameter("sortId"));
			int newsId  = Integer.parseInt(req.getParameter("newsId"));
			News news  =iNews.findNews(newsId);
			NewsHeadline headline = iNewsHeadline.getHeadlineByNewsId(newsId);
			if(headline==null){
				headline = new NewsHeadline();
				User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
				headline.setHeadTitle(headline_title);
				headline.setHeadNote(headline_note);
				headline.setNews(news);
				headline.setUser(user);
				iNewsHeadline.addNewsHeadline(headline);
				return "news.do?action=newsList&&newsSortId="+sortId;
			}
			else{
				if(headline.getHeadUrl()!=null){
					iNews.updateNewsHeadlineFlag(news);
				}
				User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
				headline.setHeadTitle(headline_title);
				headline.setHeadNote(headline_note);
				headline.setNews(news);
				headline.setUser(user);
				iNewsHeadline.updateTitle(headline);
				return "news.do?action=newsList&&newsSortId="+sortId;
			}
	}
	/**
	 * 上传头条照片
	 * @param req
	 * @param res
	 * @return
	 * @throws IOException
	 * @throws FileUploadException
	 */
	public String uploadPhoto(HttpServletRequest req,
			HttpServletResponse res) throws IOException, FileUploadException{
		int sortId = Integer.parseInt(req.getParameter("sortId"));
		int newsId  = Integer.parseInt(req.getParameter("newsId"));
		News news  = iNews.findNews(newsId);
		NewsHeadline headline = iNewsHeadline.getHeadlineByNewsId(newsId);
		if(headline==null){
			headline = new NewsHeadline();
			User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
			headline.setNews(news);
			headline.setUser(user);
			//上传头条照片
			String res_info = "";
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			try {
				List<FileItem> items= upload.parseRequest(req);
				for(FileItem item : items){
					if(!item.isFormField()){
						//说明是上传的文件
						String fileName = item.getName();
						//大于2M的头像不予上传
						if(item.getSize() > 1024*1024*2){
							res_info += "图像文件超出2M,请换一张!\n";
						}
						//控制文件的拓展名，允许.jpg,.png,.gif的图片文件
						String fileExtention = fileName.substring(fileName.lastIndexOf("."));
						if(!(fileExtention.equals(".jpg")
						|| fileExtention.equals(".png")
						|| fileExtention.equals(".gif"))){
							//不允许上传
							res_info += "抱歉，不支持的头像类型。\n 暂时只支持.jpg,.png,.gif \n";
						}
						if(res_info.length()>0){
							//文件不满足要求
							req.setAttribute("alert_info", res_info);
							return "frontClient/user/selfInfo.jsp";
						}else{
							//开始上传文件--上传到服务器目录Friend/upload/userName/head/目录下
							String root = req.getServletContext().getRealPath("/");//D:\Tomcat 7.0\wtpwebapps\Friend\
							root = root.replace("\\", "/");
							String dbFilePath = "upload/headline/";
							String uploadDir = root + dbFilePath;
							//创建目录
							File dir = new File(uploadDir);
							if(!dir.isDirectory()){
								dir.mkdirs();
							}
							//得到uuid的文件名，防止重名
							String uuidFileName = UUID.randomUUID().toString() + fileExtention;
							String filePath = uploadDir + uuidFileName;
							dbFilePath = dbFilePath + uuidFileName;
							File file = new File(filePath);
							try {
								//上传到服务器
								item.write(file);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							headline.setHeadUrl(dbFilePath);
						}
					}
					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//
			if(headline.getHeadTitle()!=null){
				iNews.updateNewsHeadlineFlag(news);
			}
			iNewsHeadline.addNewsHeadline(headline);
			return "news.do?action=newsList&newsSortId="+sortId;
		}
		else{
			String res_info = "";
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				List<FileItem> items= upload.parseRequest(req);
				for(FileItem item : items){
					if(!item.isFormField()){
						//说明是上传的文件
						String fileName = item.getName();
						//大于2M的头像不予上传
						if(item.getSize() > 1024*1024*2){
							res_info += "图像文件超出2M,请换一张!\n";
						}
						//控制文件的拓展名，允许.jpg,.png,.gif的图片文件
						String fileExtention = fileName.substring(fileName.lastIndexOf("."));
						if(!(fileExtention.equals(".jpg")
						|| fileExtention.equals(".png")
						|| fileExtention.equals(".gif"))){
							//不允许上传
							res_info += "抱歉，不支持的头像类型。\n 暂时只支持.jpg,.png,.gif \n";
						}
						if(res_info.length()>0){
							//文件不满足要求
							req.setAttribute("alert_info", res_info);
							return "frontClient/user/selfInfo.jsp";
						}else{
							//开始上传文件--上传到服务器目录Friend/upload/userName/head/目录下
							String root = req.getServletContext().getRealPath("/");//D:\Tomcat 7.0\wtpwebapps\Friend\
							root = root.replace("\\", "/");
							String dbFilePath = "upload/headline/";
							String uploadDir = root + dbFilePath;
							//创建目录
							File dir = new File(uploadDir);
							if(!dir.isDirectory()){
								dir.mkdirs();
							}
							//得到uuid的文件名，防止重名
							String uuidFileName = UUID.randomUUID().toString() + fileExtention;
							String filePath = uploadDir + uuidFileName;
							dbFilePath = dbFilePath + uuidFileName;
							File file = new File(filePath);
							try {
								//上传到服务器
								item.write(file);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							headline.setHeadUrl(dbFilePath);
						}
					}
					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(headline.getHeadTitle()!=null){
				iNews.updateNewsHeadlineFlag(news);
			}
			iNewsHeadline.updateUrl(headline);
			return "news.do?action=newsList&newsSortId="+sortId;
		}
	}
	/**
	 * 添加头条信息（在所有新闻中使用）
	 * @param req
	 * @param res
	 * @return String
	 */
	public String addHeadlineA(HttpServletRequest req,
			HttpServletResponse res){
		String headline_title= req.getParameter("headline_title");
		String headline_note = req.getParameter("headline_note");
		int newsId  = Integer.parseInt(req.getParameter("newsId"));
		News news  =iNews.findNews(newsId);
		NewsHeadline headline = iNewsHeadline.getHeadlineByNewsId(newsId);
		if(headline==null){
			headline = new NewsHeadline();
			User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
			headline.setHeadTitle(headline_title);
			headline.setHeadNote(headline_note);
			headline.setNews(news);
			headline.setUser(user);
			iNewsHeadline.addNewsHeadline(headline);
			return "news.do?action=allNewsList";
		}
		else{
			if(headline.getHeadUrl()!=null){
				iNews.updateNewsHeadlineFlag(news);
			}
			User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
			headline.setHeadTitle(headline_title);
			headline.setHeadNote(headline_note);
			headline.setNews(news);
			headline.setUser(user);
			iNewsHeadline.updateTitle(headline);
			return "news.do?action=allNewsList";
		}
	}
	/**
	 * 上传头条照片（在所有新闻中使用）
	 * @param req
	 * @param res
	 * @return
	 * @throws IOException
	 * @throws FileUploadException
	 */
	public String uploadPhotoA(HttpServletRequest req,
			HttpServletResponse res) throws IOException, FileUploadException{
		int newsId  = Integer.parseInt(req.getParameter("newsId"));
		News news  = iNews.findNews(newsId);
		NewsHeadline headline = iNewsHeadline.getHeadlineByNewsId(newsId);
		if(headline==null){
			headline = new NewsHeadline();
			User user = (User) req.getSession().getAttribute(ParamUtil.LOGIN_USER);
			headline.setNews(news);
			headline.setUser(user);
			//上传头条照片
			String res_info = "";
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			try {
				List<FileItem> items= upload.parseRequest(req);
				for(FileItem item : items){
					if(!item.isFormField()){
						//说明是上传的文件
						String fileName = item.getName();
						//大于2M的头像不予上传
						if(item.getSize() > 1024*1024*2){
							res_info += "图像文件超出2M,请换一张!\n";
						}
						//控制文件的拓展名，允许.jpg,.png,.gif的图片文件
						String fileExtention = fileName.substring(fileName.lastIndexOf("."));
						if(!(fileExtention.equals(".jpg")
						|| fileExtention.equals(".png")
						|| fileExtention.equals(".gif"))){
							//不允许上传
							res_info += "抱歉，不支持的头像类型。\n 暂时只支持.jpg,.png,.gif \n";
						}
						if(res_info.length()>0){
							//文件不满足要求
							req.setAttribute("alert_info", res_info);
							return "frontClient/user/selfInfo.jsp";
						}else{
							//开始上传文件--上传到服务器目录Friend/upload/userName/head/目录下
							String root = req.getServletContext().getRealPath("/");//D:\Tomcat 7.0\wtpwebapps\Friend\
							root = root.replace("\\", "/");
							String dbFilePath = "upload/headline/";
							String uploadDir = root + dbFilePath;
							//创建目录
							File dir = new File(uploadDir);
							if(!dir.isDirectory()){
								dir.mkdirs();
							}
							//得到uuid的文件名，防止重名
							String uuidFileName = UUID.randomUUID().toString() + fileExtention;
							String filePath = uploadDir + uuidFileName;
							dbFilePath = dbFilePath + uuidFileName;
							File file = new File(filePath);
							try {
								//上传到服务器
								item.write(file);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							headline.setHeadUrl(dbFilePath);
						}
					}
					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//
			if(headline.getHeadTitle()!=null){
				iNews.updateNewsHeadlineFlag(news);
			}
			iNewsHeadline.addNewsHeadline(headline);
			return "news.do?action=allNewsList";
		}
		else{
			String res_info = "";
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				List<FileItem> items= upload.parseRequest(req);
				for(FileItem item : items){
					if(!item.isFormField()){
						//说明是上传的文件
						String fileName = item.getName();
						//大于2M的头像不予上传
						if(item.getSize() > 1024*1024*2){
							res_info += "图像文件超出2M,请换一张!\n";
						}
						//控制文件的拓展名，允许.jpg,.png,.gif的图片文件
						String fileExtention = fileName.substring(fileName.lastIndexOf("."));
						if(!(fileExtention.equals(".jpg")
						|| fileExtention.equals(".png")
						|| fileExtention.equals(".gif"))){
							//不允许上传
							res_info += "抱歉，不支持的头像类型。\n 暂时只支持.jpg,.png,.gif \n";
						}
						if(res_info.length()>0){
							//文件不满足要求
							req.setAttribute("alert_info", res_info);
							return "frontClient/user/selfInfo.jsp";
						}else{
							//开始上传文件--上传到服务器目录Friend/upload/userName/head/目录下
							String root = req.getServletContext().getRealPath("/");//D:\Tomcat 7.0\wtpwebapps\Friend\
							root = root.replace("\\", "/");
							String dbFilePath = "upload/headline/";
							String uploadDir = root + dbFilePath;
							//创建目录
							File dir = new File(uploadDir);
							if(!dir.isDirectory()){
								dir.mkdirs();
							}
							//得到uuid的文件名，防止重名
							String uuidFileName = UUID.randomUUID().toString() + fileExtention;
							String filePath = uploadDir + uuidFileName;
							dbFilePath = dbFilePath + uuidFileName;
							File file = new File(filePath);
							try {
								//上传到服务器
								item.write(file);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							headline.setHeadUrl(dbFilePath);
						}
					}
					
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(headline.getHeadTitle()!=null){
				iNews.updateNewsHeadlineFlag(news);
			}
			iNewsHeadline.updateUrl(headline);
			return "news.do?action=allNewsList";
		}
	}
}
